<!--
 * @author luguoxiang
 * @date 2022/9/17
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <div style="margin-bottom: var(--app-space-vertical)">
    <t-button size="small" @click="all($attrs)">全选</t-button>
    <t-button size="small" @click="clear($attrs)">全不选</t-button>
    <t-button size="small" @click="fold">折叠</t-button>
    <t-button size="small" @click="expand">展开</t-button>
  </div>
  <tree-node :data="data" v-bind="$attrs" :expanded="expanded" />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import TreeNode from './TreeNode.vue';
import menuApi from './api';
import { forEach, toTreeData } from '@/soar';

function all(attrs) {
  forEach(data.value, (x: { children: string | any[]; value: any }) => {
    if (!x.children?.length) {
      if (attrs.modelValue.indexOf(x.value) === -1) {
        attrs.modelValue.push(x.value);
      }
    }
  });
}

function clear(attrs) {
  attrs.modelValue.splice(0, attrs.modelValue.length);
}

const expanded = ref([]);
function fold() {
  expanded.value = [];
}

function expand() {
  forEach(data.value, (x: { children: string | any[]; value: any }) => {
    if (x.children?.length) {
      if (expanded.value.indexOf(x.value) === -1) {
        expanded.value.push(x.value);
      }
    }
  });
}

const data = ref([]);
menuApi.query({ $soarQuery: { fields: 'id,title,parentId,type' }, queryType: 'list', pageSize: 999999 }).then((res) => {
  // 数据转换
  res = res.list.map((x: { type: any; id: any; title: any; parentId: string }) => {
    return {
      type: x.type,
      value: x.id,
      label: x.title,
      pId: x.parentId === '0' ? null : x.parentId,
    };
  });
  // 转树形数据
  data.value = toTreeData(res, 'value');
});
</script>
